package com.whiteape.book.receiver;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import com.umeng.analytics.MobclickAgent;
import com.whiteape.book.WaApp;
import com.whiteape.book.core.manager.ReadSettingManager;
import com.whiteape.book.utils.DownloadApkUtils;
import com.whiteape.book.utils.LogUtils;

public class DownloadReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
            LogUtils.d("download ok");
            long lastId = ReadSettingManager.getInstance().getLastAdDownloadId();
            long completeDownLoadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if(lastId >= 0 && lastId != completeDownLoadId){
                //判断是不是我们自己下载的apk
                LogUtils.d("not our ad apk");
                return;
            }
            MobclickAgent.onEvent(WaApp.getInstance(), "ad_download_finish");
            LogUtils.d("start to install apk");
            DownloadApkUtils.installApk(context);
            ReadSettingManager.getInstance().setLastAdDownloadId(-1);
        } else if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
            // 如果还未完成下载，用户点击Notification ，跳转到下载中心
            Intent viewDownloadIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
            viewDownloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(viewDownloadIntent);
        }
    }
}